/**
 * 百度云上传
 */

import { server_request } from "../../utils/request";
import { session_storage } from "../../utils/storage";
import uploadConfig from "../../config/upload";
import * as qiniu from "qiniu-js";
import async from 'async';

function getTasks(file, uploadId, bucketName, key) {

    let PART_SIZE = 1 * 1024 * 1024; // 指定分块大小  1Mb 一块

    let leftSize = file.size;
    let offset = 0;
    let partNumber = 1;

    let tasks = [];

    while (leftSize > 0) {
        let partSize = Math.min(leftSize, PART_SIZE);
        tasks.push({
            file: file,
            uploadId: uploadId,
            bucketName: bucketName,
            key: key,
            partNumber: partNumber,
            partSize: partSize,
            start: offset,
            stop: offset + partSize - 1
        });

        leftSize -= partSize;
        offset += partSize;
        partNumber += 1;
    }
    // console.log( "task", tasks);
    return tasks;
}

function uploadPartFile(state, client, config) {
    return (task, callback) =>{
        let blob = task.file.slice(task.start, task.stop + 1);
        // console.log( "upload blob", blob);
        // debugger;
        client.uploadPartFromBlob(task.bucketName, task.key, task.uploadId, task.partNumber, task.partSize, blob)
            .then(function(res) {
                ++state.loaded;
                // console.log( "onProgress", state);
                config.progress && config.progress( { percent: Math.floor( ( state.loaded / state.total ) * 100)});
                callback(null, res);
            })
            .catch(function(err) {
                callback(err);
            });
    };
}


function bosUpload( file, config){
    let bos_config = uploadConfig.bos.upload_config;
    // console.log( getSts());
    // getSts()
    session_storage( "bos_sts", {
        ajax_url: uploadConfig.bos.get_sts_token_url,
        errorMsg: "获取bos临时凭证失败",
        value: config.sts,
    })
        .then( (sts) => {

            if( sts != null){
                bos_config.credentials.ak = sts.credentials.ak;
                bos_config.credentials.sk = sts.credentials.sk;
                bos_config.sessionToken = sts.credentials.sessionToken;
            }

            toUpload( file, bos_config, config);
        })
        .catch( (msg, res) => {
            config.failure && config.failure( { code: 500, msg: msg, data: res});
        });
}

function toUpload( file, bos_config, config){

    let client = new baidubce.sdk.BosClient( bos_config);
    try{
        let fileFinalPath = config.fileOnlinePath;

        let key = fileFinalPath;
        let bucket = bos_config.bucket;
        let uploadId = null ;

        let options = {
        };

        client.initiateMultipartUpload( bucket, key, options)
            .then((response) => {
                uploadId = response.body.uploadId; // 开始上传，获取服务器生成的uploadId

                let deferred = baidubce.sdk.Q.defer();
                let tasks = getTasks( file, uploadId, bucket, key);
                let state = {
                    lengthComputable: true,
                    loaded: 0,
                    total: tasks.length
                };

                // 为了管理分块上传，使用了async（https://github.com/caolan/async）库来进行异步处理
                let THREADS = 2; // 同时上传的分块数量
                async.mapLimit(tasks, THREADS, uploadPartFile(state, client, config), (err, results)=>{
                    // console.log( "on finish", err, results, state);
                    if (err) {
                        deferred.reject(err);
                    } else {
                        deferred.resolve(results);
                    }
                });
                return deferred.promise;
            })
            .then( (allResponse) =>{
                let partList = [];
                allResponse.forEach(function(response, index) {
                    // 生成分块清单
                    partList.push({
                        partNumber: index + 1,
                        eTag: response.http_headers.etag
                    });
                });
                return client.completeMultipartUpload(bucket, key, uploadId, partList); // 完成上传
            })
            .then(function (res) {
                // 上传完成
                // console.log( "upload done", res);
                config.success && config.success( {
                    code: 200,
                    msg: "success",
                    data: res.body.location
                });
            })
            .catch(function (err) {
                // 上传失败，添加您的代码
                console.error("upload error", err);
                config.failure && config.failure( { code: 500, msg: "上传失败", data: err});
            });

    }catch( e){
        config.failure && config.failure( { code: 500, msg: "上传失败", data: e});
        console.error( e);
    }
}


export default function uploadFile( file, config) {
    bosUpload( file, config);
}
